const app = getApp(); // 获取全局应用实例
const baseURL = app.globalData.baseURL
Page({
  data:{
    baseURL:baseURL,
  },

  onLoad() {
    // 登录逻辑
      wx.login({
        success: res => {
          wx.request({
            url: `${baseURL}api/login/`,  // 请求后端,
            method: 'POST',
            data: { 
              code: res.code,
              avatarUrl: '',  //暂时为空
              nickName: '',   //暂时为空
            },
            success: (res) => {
              const token = res.data.token
              wx.setStorageSync('token', token)
              this.connectWebSocket(token)
            }
          })
        }
      })
  },
  //WebSocket 连接
  connectWebSocket(token) {
    const socket = wx.connectSocket({
      url: `$wss://{baseURL}/ws/chat`,  // 请求后端连接
      header: {
        'Authorization': `Bearer ${token}`
      }
    })
  
    socket.onOpen(() => {
      console.log('连接成功')
      socket.send({
        data: JSON.stringify({
          action: 'auth',
          token: token
        })
      })
    })
    
    socket.onMessage(res => {
      const data = JSON.parse(res.data)
      switch(data.type) {
        case 'chat_message':
          this.handleNewMessage(data)
          break
        case 'user_list':
          this.setData({ onlineUsers: data.users })
          break
      }
    })
  },
  //发送消息
  sendMessage(receiverId, message) {
    this.socket.send({
      data: JSON.stringify({
        action: 'message',
        receiver: receiverId,
        message: message
      })
    })
  }
  
  
});
